<?php

namespace App\Repositories\RBAC;

use App\Models\RBAC\Role;
use App\Models\RBAC\RolePermission;
use App\Models\RBAC\UserRole;
use App\Repositories\BaseRepositoryEloquent;
use Illuminate\Support\Collection;

/**
 * Class RoleRepositoryEloquent.
 *
 * @package namespace App\Repositories;
 */
class RoleRepositoryEloquent extends BaseRepositoryEloquent implements RoleRepository
{

    /**
     * @var array
     */
    protected $fieldSearchable = [
        'name'=> "like",
        'display_name' => "like",
    ];

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Role::class;
    }


    /**
     * 判断 某角色 下 是否有用户
     * @param $role_id
     * User: Zhangxy
     * Date: 2018-08-15
     * @return mixed
     */
    public function hasUsers($role_id)
    {
        $count = UserRole::where('role_id', $role_id)->count();
        return $count ? true : false;
    }

    /**
     * 判断 某角色 下 是否有 权限项
     * @param $role_id
     * User: Zhangxy
     * Date: 2018-08-15
     * @return mixed
     */
    public function hasPermItems($role_id)
    {
        $count = RolePermission::where('role_id', $role_id)->count();
        return $count ? true : false;
    }

    /**
     * 保存某角色的所有权限项
     * @param $id
     * @param array $perms
     * @param int $root_perm_id
     * User: Zhangxy
     * Date: 2018-08-15
     * @return bool
     */
    public function savePermissions($id, $perms = [], $root_perm_id = 0)
    {
        $role = $this->model->find($id);
        $extraPerms = [];
        if (!empty($perms)) {
            // 不要把 root_perm_id 作为额外数据 入库
            foreach ($perms as $index => $perm) {
                $extraPerms[$perm] = ['root_permission_id' => $root_perm_id];
            }
        }

        $role->perms($root_perm_id)->sync($extraPerms);

        return true;
    }


    /**
     * 获取某角色的所有权限项ID
     * @param $role_ids
     * User: Zhangxy
     * Date: 2018-08-15
     * @return array
     */
    public function attachedPermissionIds($role_ids)
    {

        $rpIds = [];
        if ($role_ids) {
            if (!is_array($role_ids)) {
                $role_ids = [$role_ids];
            }

            $prInfo = RolePermission::whereIn("role_id", $role_ids)->get();
            if ($prInfo) {
                $prInfo->each(function ($item) use (&$rpIds) {
                    $rpIds[] = $item->permission_id;
                });
            }
        }
        return $rpIds;


    }

    /**
     * 获取某角色的所有权限项
     * @param $role_ids
     * @param array $permWhere
     * User: Zhangxy
     * Date: 2018-08-15
     * @return array
     */
    public function rolePermissions($role_ids, $permWhere = [])
    {
        $rolePerms = [];

        if (!empty($role_ids)) {
            $with = 'perms';
            if (!empty($permWhere)) {
                $with = ['perms' => function ($query) use ($permWhere) {
                    foreach ($permWhere as $field => $value) {
                        $query->where($field, $value);
                    }
                }];
            }

            $roles = $this->with($with)->find($role_ids);

            if (!is_empty($roles)) {
                if (!($roles instanceof Collection)) {
                    $roles = [$roles];
                }
                foreach ($roles as $index => $role) {
                    $perms = $role->perms;
                    if (!is_empty($perms)) {
                        foreach ($perms as $item) {
                            $rolePerms[$item->id] = $item;
                        }
                    }
                }
            }
        }
        return $rolePerms;
    }

    /**
     * 获取某角色的所有菜单项
     * @param $role_ids
     * User: Zhangxy
     * Date: 2018-08-15
     * @return array
     */
    public function roleMenus($role_ids)
    {
        $menus = [];
        $rootMenuIds = [];
        $permissionRepository = app()->make(PermissionRepository::class);
        $rootMenus = $permissionRepository->rootMenus();
        if (!empty($rootMenus)) {
            $rootMenuIds = array_keys($rootMenus->toArray());
            foreach ($rootMenuIds as $index => $rootMenuId) {
                $menus[$rootMenuId] = [];
            }
        }

        $attachedMenus = $this->rolePermissions($role_ids, ['is_menu' => 1]);

        if (!is_empty($attachedMenus)) {
            foreach ($attachedMenus as $index => $attachedMenu) {
                // 一级
                if (in_array($attachedMenu->id, $rootMenuIds)) {
                    $menus[$attachedMenu->id]['self'] = $attachedMenu;
//                } elseif (in_array($attachedMenu->pid, $rootMenuIds)) {
//                    // 二级
//                    $menus[$attachedMenu->pid]['subMenus'][$attachedMenu->id] = $attachedMenu;
                } else {
//                    dd($attachedMenu);
                    // 三级
                    if (isset($attachedMenus[$attachedMenu->pid])) {
                        $secondMenu = $attachedMenus[$attachedMenu->pid];
                    } else {
                        $secondMenu = $attachedMenu->parentPermission;
                    }
                    $menus[$secondMenu->pid]['subMenus'][$attachedMenu->id] = $attachedMenu;
                }
            }
        }
        return $menus;

    }

}
